package com.sservice.web.controller.admin;

import com.sservice.common.CompareObject;
import com.sservice.common.Constants;
import com.sservice.common.SameUrlData;
import com.sservice.model.dao.IGoodsDao;
import com.sservice.model.vo.PurchaseVo;
import com.sservice.urp.entity.User;
import com.sservice.urp.vo.UserVo;
import com.sservice.service.service.IGoodsService;
import com.sservice.service.service.PurchaseLogService;
import com.sservice.service.service.PurchaseOrderService;
import com.sservice.service.service.PurchaseService;
import com.sservice.base.entity.dto.BaseResult;
import com.sservice.base.entity.dto.ListResult;
import com.sservice.base.entity.dto.Pagination;
import com.sservice.model.entity.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin/purchase/")
public class PurchaseController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private PurchaseService service;
    @Autowired
    private PurchaseLogService serviceLog;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IGoodsDao goodsDao;
    @Autowired
    private PurchaseOrderService orderService;

    public String toString(Object obj) {
        Map fieldKeyValue = new HashMap();
        fieldKeyValue.put("price", "价格");
        fieldKeyValue.put("qualitySpec", "质量规格");
        fieldKeyValue.put("qualityStandard", "质量标准");
        fieldKeyValue.put("packSpec", "包装规格");
        fieldKeyValue.put("order", "排序号");
        fieldKeyValue.put("online", "在线状态");
        fieldKeyValue.put("ratioSale", "销售员佣金");
        fieldKeyValue.put("ratioManager", "销售经理佣金");
        fieldKeyValue.put("remark", "备注");
        fieldKeyValue.put("deliverPlace", "供货地");
        List<String> strArr = new ArrayList<String>();
        Map map = (Map) obj;
        for (Object str : map.keySet()) {

            strArr.add(fieldKeyValue.get(str).toString() + map.get(str).toString());

        }
        return StringUtils.join(strArr, ",");
    }

    public void log(Object content, HttpServletRequest request, Integer purchaseId) {
        PurchaseLog log = new PurchaseLog();
        if (content instanceof Map) {
            log.setContent(toString(content));
        } else {
            log.setContent(content.toString());
        }
        if (log.getContent().length() == 0) {
            return;
        }

        log.setPurchaseId(purchaseId.toString());

        User user = (User) request.getSession().getAttribute(Constants.USER);
        log.setCreator(user.getId());
        log.setIp(Constants.getIP(request)); // 获取IP地址
        serviceLog.insertSelective(log);
    }

    /***
     * 分页查询
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/query", method = RequestMethod.GET)
    public ListResult query(PurchaseVo arg, HttpSession session) {

        List<PurchaseVo> list_order = service.queryByPage(arg);
        int total = service.queryCount(arg);
        Pagination page = new Pagination(arg.getPage(), total, arg.getSize());
        ListResult res = new ListResult(true, list_order);
        res.setPage(page);
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/queryWithAuth", method = RequestMethod.GET)
    public ListResult queryWithAuth(PurchaseVo arg, HttpSession session) {
        UserVo user = (UserVo) session.getAttribute(Constants.USER);
        Boolean isManger = false;
        if (1 == user.getId()) {
            isManger = true;
        }
        if (!isManger) { //运营账户判断判断
            Goods g = new Goods();
            g.setOperatorId(String.valueOf(user.getId()));
            List<Goods> list = goodsDao.queryFindInSet(g);
            if (!isManger && 0 == list.size()) {
                return new ListResult(false, "非运营或超级管理员角色账号，无权访问!", 403);
            }
            List<String> lstr = new ArrayList<String>();
            for (Goods item : list) {
                if (("," + item.getOperatorId() + ",").indexOf("," + user.getId() + ",") > -1) {
                    lstr.add(String.valueOf(item.getId()));
                }
            }
            if (lstr.size() > 0) {
                arg.setList(lstr);
            }
        }

        List<PurchaseVo> list_order = service.queryByPage(arg);
        int total = service.queryCount(arg);
        Pagination page = new Pagination(arg.getPage(), total, arg.getSize());
        ListResult res = new ListResult(true, list_order);
        res.setPage(page);
        return res;
    }


    @ResponseBody
    @RequestMapping(value = "/get", method = RequestMethod.GET)
    public BaseResult<Purchase> get(PurchaseVo arg, HttpSession session) {
        Purchase p = service.selectByPrimaryKey(arg.getId());
        return new BaseResult<Purchase>(true, p);
    }

    @ResponseBody
    @RequestMapping(value = "/report", method = RequestMethod.GET)
    public BaseResult<Purchase> report(PurchaseVo arg, HttpSession session) {
        Purchase p = service.selectByPrimaryKey(arg.getId());
        return new BaseResult<Purchase>(true, p);
    }

    @SameUrlData
    @ResponseBody
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public BaseResult create(Purchase arg, HttpSession session, HttpServletRequest request) {
        User user = (User) session.getAttribute(Constants.USER);
        arg.setCreator(String.valueOf(user.getId()));
        int list_order = service.insertSelective(arg);
        if (list_order > 0) {
            log("创建", request, arg.getId());
        }
        BaseResult res = new BaseResult(true, list_order);
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public BaseResult update(Purchase arg, HttpServletRequest request) {
        Purchase purchase = service.selectByPrimaryKey(arg.getId());
        int list_order = service.updateByPrimaryKeySelective(arg);
        if (list_order > 0) {
            Map<String, Object> res = CompareObject.contrastObj(arg, purchase);
            log(res, request, arg.getId());
        }
        BaseResult res = new BaseResult(true, list_order);
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/plus", method = RequestMethod.POST)
    public BaseResult plus(Purchase arg, HttpServletRequest request) {
        Purchase purchase = service.selectByPrimaryKey(arg.getId());
        BigDecimal number = arg.getNumber();
        arg.setNumber(arg.getNumber().add(purchase.getNumber()));
        int list_order = service.updateByPrimaryKeySelective(arg);
        if (list_order > 0) {
            Map<String, Object> res = CompareObject.contrastObj(arg, purchase);
            log("增加采购数量" + number, request, arg.getId());
        }
        BaseResult res = new BaseResult(true, list_order);
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public BaseResult delete(Purchase arg, HttpServletRequest request) {
        PurchaseOrder po = new PurchaseOrder();
        po.setPurchaseId(String.valueOf(arg.getId()));
        int orderCount = orderService.countByPurchaseId(po);
        if (orderCount > 0) {
            return new BaseResult(false, "采购单存在关联数据,不能删除!", 403);
        }
        int list_order = service.deleteByPrimaryKey(arg.getId());
        BaseResult res = new BaseResult(true, list_order);
        if (list_order > 0) {
            log("删除", request, arg.getId());
        }
        return res;
    }
}